<template>
  <div>
    <div style="display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:12px">
      <div style="display:flex; align-items:center; gap:8px">
        <el-input v-model="searchQuery" placeholder="搜索配置名或值" clearable @clear="clearSearch" style="width:360px" />
      </div>
      <div>
        <el-button type="primary" @click="openAdd" v-if="canAdd">新增配置</el-button>
      </div>
    </div>

    <el-table :data="configs" stripe border style="width:100%" remote @sort-change="onSortChange" @header-click="onHeaderClick">
      <el-table-column label="序号" width="80">
        <template #default="{ $index }">{{ (page - 1) * pageSize + $index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="config_name" label="配置名" sortable />
      <el-table-column prop="config_value" label="配置值" sortable />
      <el-table-column prop="remarks" label="备注" />
      <el-table-column label="操作" width="130">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)" v-if="canEdit">编辑</el-button>
          <el-button size="small" type="danger" @click="remove(row)" style="margin-left:8px" v-if="canDelete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:12px; display:flex; justify-content:flex-end; align-items:center">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[5,10,20]"
        :total="total"
        @current-change="gotoPage"
        @size-change="onSizeChange"
      />
    </div>

    <el-alert v-if="error" type="error" :title="error" show-icon style="margin-top:12px" />

    <el-dialog :title="editing.id ? '编辑配置' : '新增配置'" v-model="showModal" width="520px">
      <el-form ref="formRef" :model="editing" :rules="rules" label-width="110px">
        <el-form-item prop="config_name">
          <template #label>配置名</template>
          <el-input v-model="editing.config_name" />
        </el-form-item>

        <el-form-item prop="config_value">
          <template #label>配置值</template>
          <el-input v-model="editing.config_value" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" rows="3" v-model="editing.remarks" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '../stores/auth'

const auth = useAuthStore()
const MENU_CODE = '0106'
const canAdd = computed(() => auth.hasPermission(MENU_CODE, '新增'))
const canEdit = computed(() => auth.hasPermission(MENU_CODE, '编辑'))
const canDelete = computed(() => auth.hasPermission(MENU_CODE, '删除'))

const configs = ref<any[]>([])
const error = ref('')

// search
const searchQuery = ref('')
const searchTimer = ref<number | null>(null)

// pagination
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))

// sorting
const sortBy = ref<string | null>(null)
const sortOrder = ref<'asc' | 'desc' | null>(null)

const showModal = ref(false)
const editing = reactive<any>({ id: null, config_name: '', config_value: '', remarks: '' })
const formRef = ref<any>(null)

const rules = {
  config_name: [{ required: true, message: '请输入配置名', trigger: ['blur', 'change'] }],
  config_value: [{ required: true, message: '请输入配置值', trigger: ['blur', 'change'] }]
}

async function load() {
  error.value = ''
  try {
    // if searching, fetch all and filter client-side for simplicity
    const q = String(searchQuery.value || '').trim().toLowerCase()
    if (q || !sortBy.value) {
      const params = new URLSearchParams()
      params.set('page', String(page.value))
      params.set('limit', String(pageSize.value))
      if (sortBy.value) params.set('sort_by', sortBy.value)
      if (sortOrder.value) params.set('sort_order', sortOrder.value)

      const res = await auth.apiFetch(`/configs?${params.toString()}`)
      configs.value = (res.configs || res || []).map((c: any) => ({ ...c }))
      total.value = typeof res.total === 'number' ? res.total : configs.value.length

      // apply simple client-side search when q is present
      if (q) {
        const filtered = configs.value.filter((c: any) => {
          return (String(c.config_name || '').toLowerCase().includes(q) || String(c.config_value || '').toLowerCase().includes(q) || String(c.remarks || '').toLowerCase().includes(q))
        })
        total.value = filtered.length
        configs.value = filtered
      }
    } else {
      // fetch paged+sorted
      const params = new URLSearchParams()
      params.set('page', String(page.value))
      params.set('limit', String(pageSize.value))
      if (sortBy.value) params.set('sort_by', sortBy.value)
      if (sortOrder.value) params.set('sort_order', sortOrder.value)
      const res = await auth.apiFetch(`/configs?${params.toString()}`)
      configs.value = (res.configs || res || []).map((c: any) => ({ ...c }))
      total.value = typeof res.total === 'number' ? res.total : configs.value.length
    }
  } catch (e) {
    configs.value = []
    total.value = 0
    error.value = '加载失败'
  }
}

onMounted(() => {
  load()
})

function openAdd() {
  if (!canAdd.value) { ElMessage.warning('没有新增权限'); return }
  editing.id = null
  editing.config_name = ''
  editing.config_value = ''
  editing.remarks = ''
  showModal.value = true
}

function openEdit(c: any) {
  if (!canEdit.value) { ElMessage.warning('没有编辑权限'); return }
  editing.id = c.id
  editing.config_name = c.config_name || ''
  editing.config_value = c.config_value || ''
  editing.remarks = c.remarks || ''
  showModal.value = true
}

function closeModal() { showModal.value = false }

async function submit() {
  error.value = ''
  try {
    if (formRef.value) await formRef.value.validate()
    else {
      if (!editing.config_name || typeof editing.config_value === 'undefined') { error.value = '请填写必填字段'; ElMessage.error(error.value); return }
    }

    if (editing.id) {
      if (!canEdit.value) { ElMessage.error('没有编辑权限'); return }
      await auth.apiFetch(`/configs/${editing.id}`, { method: 'PUT', body: JSON.stringify({ config_name: editing.config_name, config_value: editing.config_value, remarks: editing.remarks }) })
      ElMessage.success('编辑成功')
    } else {
      if (!canAdd.value) { ElMessage.error('没有新增权限'); return }
      await auth.apiFetch(`/configs`, { method: 'POST', body: JSON.stringify({ config_name: editing.config_name, config_value: editing.config_value, remarks: editing.remarks }) })
      ElMessage.success('新增成功')
    }
    closeModal()
    load()
  } catch (e: any) {
    try { const body = await e.json(); error.value = body.message || '操作失败' } catch { error.value = '操作失败' }
    ElMessage.error(error.value)
  }
}

async function remove(c: any) {
  error.value = ''
  if (!canDelete.value) { ElMessage.warning('没有删除权限'); return }
  ElMessageBox.confirm(`确定删除配置 ${c.config_name} ?`, '删除确认', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      try {
        await auth.apiFetch(`/configs/${c.id}`, { method: 'DELETE' })
        ElMessage.success('删除成功')
        if (configs.value.length === 1 && page.value > 1) page.value = page.value - 1
        load()
      } catch (e: any) {
        try { const body = await e.json(); error.value = body.message || '删除失败' } catch { error.value = '删除失败' }
        ElMessage.error(error.value)
      }
    })
    .catch(() => {})
}

function gotoPage(n: number) { if (n < 1) n = 1; if (n > totalPages.value) n = totalPages.value; page.value = n; load() }
function onSizeChange(size: number) { pageSize.value = size; gotoPage(1) }

function onSortChange(sort: any) {
  const prop = sort && sort.prop ? sort.prop : (sort && sort.column ? (sort.column.property ?? sort.column.prop ?? null) : null)
  const orderRaw = sort && sort.order ? sort.order : null
  let order: string | null = null
  if (orderRaw) {
    order = (orderRaw === 'ascending' || orderRaw === 'asc') ? 'asc' : 'desc'
  } else if (prop && prop === sortBy.value) {
    if (sortOrder.value === 'asc') order = 'desc'
    else if (sortOrder.value === 'desc') order = null
    else order = 'asc'
  }

  if (!prop || !order) { sortBy.value = null; sortOrder.value = null }
  else { sortBy.value = String(prop); sortOrder.value = order as 'asc' | 'desc' }
  page.value = 1
  load()
}

function onHeaderClick(column: any) {
  if (!column) return
  const prop = column.property ?? column.prop ?? null
  if (!prop) return
  if (!column.sortable && column.sortable !== 'custom' && column.sortable !== true) return
  if (sortBy.value !== prop) { sortBy.value = String(prop); sortOrder.value = 'asc' }
  else { if (sortOrder.value === 'asc') sortOrder.value = 'desc'; else if (sortOrder.value === 'desc') { sortBy.value = null; sortOrder.value = null } else sortOrder.value = 'asc' }
  page.value = 1
  load()
}

function clearSearch() { searchQuery.value = ''; page.value = 1; load() }
watch(searchQuery, () => { if (searchTimer.value) clearTimeout(searchTimer.value); searchTimer.value = window.setTimeout(() => { page.value = 1; load() }, 350) })
</script>

<style scoped>
/* minimal styles */
</style>
